package com.jeecg.modules.jmreport.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeecg.modules.jmreport.util.encryption.AesEncryptUtil;
import com.jeecg.modules.jmreport.util.encryption.EncryptedString;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 积木报表-设置默认首页跳转
 */
@Controller
public class IndexController {
    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("name", "jimureport");
        return "jmreport/list"; // 视图重定向 - 跳转
    }

    // 新增处理 /login/login-server 请求的方法
    @GetMapping("/login/login-server/{tenantId}")
    public String loginServer(@PathVariable String tenantId, Model model, HttpServletRequest request, HttpServletResponse response) {

        // 设置自定义响应头，将 AES 加密所需的 key 和 iv 传递给前端
        response.addHeader("X-AES-Key", EncryptedString.key);
        response.addHeader("X-AES-IV", EncryptedString.iv);

        model.addAttribute("tenantId", tenantId);
        return "login/login-server-page";
    }

    private String getTenantId(String domain) {
        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClients.createDefault();
        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("domain", domain + ".suzi-info.com");

        // 拼接请求参数到 URL
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (queryString.length() > 0) {
                queryString.append("&");
            }
            try {
                queryString.append(URLEncoder.encode(entry.getKey(), String.valueOf(StandardCharsets.UTF_8)))
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), String.valueOf(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                logger.error("编码参数时出错", e);
            }
        }

        String baseUrl = "https://www.suzi-info.com:8099/jeecg-boot/saas/data/get";
        String fullUrl = baseUrl + "?" + queryString.toString();

        // 创建 HttpGet 请求对象
        HttpGet httpGet = new HttpGet(fullUrl);
        logger.info("发送的 GET 请求 URL: {}", fullUrl);

        String tenantId = "22";
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpGet);

            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取响应内容
                String responseBody = EntityUtils.toString(response.getEntity());
                tenantId = responseBody;
                logger.info("获取到的 tenantId: {}", tenantId);
            } else {
                logger.error("请求失败，状态码: {}", response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            logger.error("请求发生错误", e);
        } finally {
            // 释放连接
            httpGet.releaseConnection();
        }

        return tenantId;
    }

    @PostMapping("/login/login-submit")
    public String loginSubmit(@RequestParam String username, @RequestParam String password, @RequestParam String tenant, Model model) throws Exception {
        logger.info("用户登录: 用户名={}, 租户={}", username, tenant);
        String tenantId = getTenantId(tenant);
        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 请求对象
        HttpPost httpPost = new HttpPost("https://www.suzi-info.com:8099/jeecg-boot/sys/login"); // 替换为实际的登录 URL

        // 添加请求头
        httpPost.addHeader("X-Saas-Tenant", tenantId);
        httpPost.addHeader("Content-Type", "application/json");

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password );
//        AesEncryptUtil.encrypt(password, EncryptedString.key,EncryptedString.iv)
        params.put("tenant", tenant);
        params.put("captchaFlag","true");

        String token = null;
        try {
            // 将参数转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonBody = objectMapper.writeValueAsString(params);
            logger.info("发送的 JSON 请求体: {}", jsonBody); // 打印请求体，方便调试

            // 设置请求体
            httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);

            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取响应内容
                String responseBody = EntityUtils.toString(response.getEntity());
                // 解析 JSON 响应获取 token
                Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
                Map<String,Object> resultMap = (Map<String,Object>) responseMap.get("result");
                token = (String) resultMap.get("token");
                logger.info("登录成功，token: {}", token);
            } else {
                logger.error("登录失败，状态码: {}", response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            logger.error("登录请求发生错误", e);
        } finally {
            // 释放连接
            httpPost.releaseConnection();
        }

        // 检查 token 是否为 null
        if (token == null) {
            token = "未获取到 Token";
        }

        // 将 token 传递到新页面
        model.addAttribute("token", token);
        model.addAttribute("tenantId",tenantId);
        return "login/success-page";
    }
}